"""
SqlAlchermy ORM关系 - 一对一
"""
import os
import sys

path = os.path.dirname(__file__)
sys.path.append(os.path.join(path, '..'))

from datetime import datetime
from sqlalchemy import Column, Integer, String, Date, ForeignKey
from sqlalchemy.orm import relationship, backref
from conf.mysql_config import SESSION, BASE


class HolidayOrm(BASE):
    __tablename__ = 'holiday'
    id = Column(Integer, autoincrement=True, primary_key=True)
    holiday = Column(Date, comment='节假日', doc={'zh': '节假日'})

    def __str__(self):
        return f'<HolidayOrm holiday={self.holiday}>'

    __repr__ = __str__


class HolidayExtendOrm(BASE):
    __tablename__ = 'holiday_extend'
    id = Column(Integer, autoincrement=True, primary_key=True)
    holiday_desc = Column(String(50), comment='节假日描述', doc={'zh': '节假日描述'})
    holiday_id = Column(Integer, ForeignKey('holiday.id'))
    # 设置uselist关键字参数为False
    holiday = relationship('HolidayOrm', backref=backref('extend', uselist=False))

    def __str__(self):
        return f'<HolidayExtendOrm holiday_desc={self.holiday_desc}>'

    __repr__ = __str__


BASE.metadata.create_all()


def add_data():
    holiday = HolidayOrm(holiday=datetime(year=2022, month=1, day=1).date())
    # holiday.extend.append(HolidayExtendOrm(holiday_desc='元旦节'))
    holiday.extend = HolidayExtendOrm(holiday_desc='元旦节')
    SESSION.add(holiday)
    SESSION.commit()


if __name__ == '__main__':
    add_data()
